package com.jzo2o.orders.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.DbRuntimeException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;

import com.jzo2o.api.foundations.AddressBookApi;
import com.jzo2o.api.foundations.ServeApi;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.api.orders.dto.response.OrderResDTO;
import com.jzo2o.api.orders.dto.response.OrderSimpleResDTO;
import com.jzo2o.api.trade.NativePayApi;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.TradingApi;
import com.jzo2o.api.trade.dto.request.NativePayReqDTO;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.api.trade.dto.response.NativePayResDTO;
import com.jzo2o.api.trade.dto.response.TradingResDTO;
import com.jzo2o.api.trade.enums.PayChannelEnum;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.enums.EnableStatusEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.DateUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderRefundStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.mapper.OrdersRefundMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersCanceled;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.base.model.domain.OrdersServe;
import com.jzo2o.orders.base.model.dto.OrderUpdateStatusDTO;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.model.dto.request.OrdersPayReqDTO;
import com.jzo2o.orders.manager.model.dto.request.PlaceOrderReqDTO;
import com.jzo2o.orders.manager.model.dto.response.OrdersPayResDTO;
import com.jzo2o.orders.manager.model.dto.response.PlaceOrderResDTO;

import com.jzo2o.orders.manager.porperties.TradeProperties;
import com.jzo2o.orders.manager.service.IOrdersCanceledService;
import com.jzo2o.orders.manager.service.IOrdersManagerService;


import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.jzo2o.orders.base.constants.FieldConstants.SORT_BY;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-10
 */
@Slf4j
@Service
public class OrdersManagerServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersManagerService {
    @Resource
   private AddressBookApi addressBookApi;
    @Resource
    ServeApi serveApi;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    IOrdersManagerService iOrdersManagerService;
    @Resource
    OrdersRefundMapper ordersRefundMapper;
    @Resource
    RefundRecordApi refundRecordApi;
    @Resource
    CouponApi couponApi;

    @Override
    public List<Orders> batchQuery(List<Long> ids) {
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.<Orders>lambdaQuery().in(Orders::getId, ids).ge(Orders::getUserId, 0);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Orders queryById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 滚动分页查询
     *
     * @param currentUserId 当前用户id
     * @param ordersStatus  订单状态，0：待支付，100：派单中，200：待服务，300：服务中，400：待评价，500：订单完成，600：已取消，700：已关闭
     * @param sortBy        排序字段
     * @return 订单列表
     */
    @Override
    public List<OrderSimpleResDTO> consumerQueryList(Long currentUserId, Integer ordersStatus, Long sortBy) {
        //1.构件查询条件
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.<Orders>lambdaQuery()
                .eq(ObjectUtils.isNotNull(ordersStatus), Orders::getOrdersStatus, ordersStatus)
                .lt(ObjectUtils.isNotNull(sortBy), Orders::getSortBy, sortBy)
                .eq(Orders::getUserId, currentUserId)
                .eq(Orders::getDisplay, EnableStatusEnum.ENABLE.getStatus());
        Page<Orders> queryPage = new Page<>();
        queryPage.addOrder(OrderItem.desc(SORT_BY));
        queryPage.setSearchCount(false);

        //2.查询订单列表
        Page<Orders> ordersPage = baseMapper.selectPage(queryPage, queryWrapper);
        List<Orders> records = ordersPage.getRecords();
        List<OrderSimpleResDTO> orderSimpleResDTOS = BeanUtil.copyToList(records, OrderSimpleResDTO.class);
        return orderSimpleResDTOS;

    }
    /**
     * 根据订单id查询
     *
     * @param id 订单id
     * @return 订单详情
     */
    @Override
    public OrderResDTO getDetail(Long id) {
        Orders orders = queryById(id);
        OrderResDTO orderResDTO = BeanUtil.toBean(orders, OrderResDTO.class);
        return orderResDTO;
    }

    /**
     * 订单评价
     *
     * @param ordersId 订单id
     */
    @Override
    @Transactional
    public void evaluationOrder(Long ordersId) {
//        //查询订单详情
//        Orders orders = queryById(ordersId);
//
//        //构建订单快照
//        OrderSnapshotDTO orderSnapshotDTO = OrderSnapshotDTO.builder()
//                .evaluationTime(LocalDateTime.now())
//                .build();
//
//        //订单状态变更
//        orderStateMachine.changeStatus(orders.getUserId(), orders.getId().toString(), OrderStatusChangeEventEnum.EVALUATE, orderSnapshotDTO);
    }

    private Long genateOrdeByid(){
        //通过redis的原子递增策略
        Long key = redisTemplate.opsForValue().increment("key", 1);
        //生成订单号
       Long orderid= DateUtils.getFormatDate(LocalDateTime.now(),"yyMMdd")*10000000000000L+key;
        return orderid;
    }


    public void add(Orders orders){

        boolean save = this.save(orders);
    }

    @Override
    @Transactional
    public PlaceOrderResDTO place(PlaceOrderReqDTO placeOrderReqDTO){
        //地址簿id
        Long addressBookId = placeOrderReqDTO.getAddressBookId();
        //验证服务地址
        AddressBookResDTO getapi = addressBookApi.deataoil(addressBookId);
        if(Objects.isNull(getapi)){
            throw new BadRequestException("预约地址异常,无法下单");
        }
        //服务
        ServeAggregationResDTO byId = serveApi.findById(placeOrderReqDTO.getServeId());

        //服务下架不可下单
         if(byId==null||byId.getSaleStatus()!=2){
             throw new BadRequestException("服务不可用");
         }
        //下单前数据准备
        Orders orders = new Orders();
        //订单
         orders.setId(genateOrdeByid());
         //userid,从thread
        orders.setUserId(UserContext.currentUserId());
        //服务id
        orders.setServeId(byId.getId());
        //服务项id
        orders.setServeItemId(byId.getServeItemId());
        orders.setServeItemName(byId.getServeItemName());
        orders.setServeItemImg(byId.getServeItemImg());
        orders.setUnit(byId.getUnit());
        //服务类型信息
        orders.setServeTypeId(byId.getServeTypeId());
        orders.setServeTypeName(byId.getServeTypeName());

        //订单状态
        orders.setOrdersStatus(0);
        //支付状态，初始化一个空状态
        orders.setPayStatus(OrderPayStatusEnum.NO_PAY.getStatus());
        //服务时间
        orders.setServeStartTime(placeOrderReqDTO.getServeStartTime());
        //城市编码
        orders.setCityCode(byId.getCityCode());
        //地理位置
        orders.setLon(getapi.getLon());
        orders.setLat(getapi.getLat());

        String stringBuffer = new StringBuffer(getapi.getProvince())
                .append(getapi.getCity())
                .append(getapi.getCounty())
                .append(getapi.getAddress())
                .toString();
        orders.setServeAddress(stringBuffer);
        //联系人
        orders.setContactsName(getapi.getName());
        orders.setContactsPhone(getapi.getPhone());
        //价格
         orders.setPrice(byId.getPrice());
         //数量
        orders.setPurNum(NumberUtils.null2Default(placeOrderReqDTO.getPurNum(),1));
         //订单价格 价格*数量
        BigDecimal bigDecimal = new BigDecimal(0.01);
        orders.setTotalAmount(bigDecimal);
        //优惠金额 当前默认0
        orders.setDiscountAmount(BigDecimal.ZERO);
        //实付金额 订单总金额-优惠金额
        orders.setRealPayAmount(bigDecimal);
        //排序字段 根据服务开始时间转为毫秒时间戳+订单后5位
       Long sortByid= DateUtils.toEpochMilli(orders.getServeStartTime())+orders.getId()%100000;
       orders.setSortBy(sortByid);
       //保存订单
        add(orders);

            return new PlaceOrderResDTO(orders.getId());
        
    }
    @Resource
    private TradeProperties tradeProperties;
    @Resource
    private NativePayApi nativePayApi;
    @Resource
    TradingApi tradingApi;
    /**
    * @description
    * @author Gaosir
    * @return * @return: com.jzo2o.orders.manager.model.dto.response.OrdersPayResDTO
    * 支付接口
    * @date 2024/8/28 22:13
    */

    @Override
    public OrdersPayResDTO pay(Long id, OrdersPayReqDTO ordersPayReqDTO) {

        //1根据id查询订单
        Orders orders = this.getById(id);
        //2,效验订单是否存在
        if(ObjectUtils.isNull(orders)){
            throw new CommonException("订单不存在");
        }
        //说明 已经支付过了  并且 订单号 不是空的直接返回订单信息即可
        if(OrderPayStatusEnum.PAY_SUCCESS.getStatus()==orders.getPayStatus()&&ObjectUtils.isNotNull(orders.getTradingOrderNo())){

            OrdersPayResDTO ordersPayResDTO = new OrdersPayResDTO();
            BeanUtil.copyProperties(orders,ordersPayResDTO);
            //把交易订单号返回
            ordersPayResDTO.setProductOrderNo(orders.getId());
            return ordersPayResDTO;
        }else {
            //没有支付过 生成二维码
           NativePayResDTO nativePayResDTO= generatecode(orders, ordersPayReqDTO.getTradingChannel());
            OrdersPayResDTO ordersPayResDTO = BeanUtil.toBean(nativePayResDTO, OrdersPayResDTO.class);
            return ordersPayResDTO;
        }
    }

    @Override
    public OrdersPayResDTO payResDTO(Long id) {

        //查询订单表
        Orders orders = baseMapper.selectById(id);
        if(!ObjectUtils.isNotNull(orders)){
            throw new CommonException("订单不存在");
        }

        //支付结果
        Integer payStatus = orders.getPayStatus();
        //未支付且已经存在支付服务的交易单号此时远程调用支付方服务查询支付结果
        if(OrderPayStatusEnum.NO_PAY.getStatus()==payStatus&&ObjectUtils.isNotNull(orders.getTradingOrderNo())){
            //远程调用支付服务查询支付结果
            TradingResDTO tradResultByTradingOrderNo = tradingApi.findTradResultByTradingOrderNo(orders.getTradingOrderNo());;
            if(ObjectUtils.isNotNull(tradResultByTradingOrderNo)&&ObjectUtils.equals(tradResultByTradingOrderNo.getTradingState(), TradingStateEnum.YJS)){

                //设置订单的支付状态成功
                TradeStatusMsg build = TradeStatusMsg.builder()
                        .productOrderNo(orders.getId())
                        .tradingChannel(tradResultByTradingOrderNo.getTradingChannel())
                        .statusCode(TradingStateEnum.YJS.getCode())
                        .tradingOrderNo(tradResultByTradingOrderNo.getTradingOrderNo())
                        .transactionId(tradResultByTradingOrderNo.getTransactionId())
                        .build();

                pageSuccess(build);
                //构造返回数据
                OrdersPayResDTO ordersPayResDTO = BeanUtils.toBean(build, OrdersPayResDTO.class);
                ordersPayResDTO.setPayStatus(OrderPayStatusEnum.PAY_SUCCESS.getStatus());
                return ordersPayResDTO;
            }
        }

        //3.订单的支付状态为成功直接返回
        OrdersPayResDTO ordersPayResDTO = new OrdersPayResDTO();
        ordersPayResDTO.setPayStatus(payStatus);
        ordersPayResDTO.setProductOrderNo(orders.getId());
        ordersPayResDTO.setTradingOrderNo(orders.getTradingOrderNo());
       ordersPayResDTO.setTradingChannel(orders.getTradingChannel());

       return ordersPayResDTO;
    }

    public void pageSuccess(TradeStatusMsg tradeStatusMsg) {

        //查询订单
        Orders orders = baseMapper.selectById(tradeStatusMsg.getProductOrderNo());
        if(ObjectUtils.isNull(orders)){
            throw new CommonException("订单不存在");
        }
        //效验支付状态如果不是待支付状态则不作处理
        if(ObjectUtils.notEqual(OrderPayStatusEnum.NO_PAY.getStatus(),orders.getPayStatus())){
            System.out.println("更新订单支付成功，当前订单:{支付状态不是待支付状态}"+orders.getId());
            return;
        }

        //第三方支付单号效验
        if(ObjectUtils.isNull(tradeStatusMsg.getTransactionId())){
            throw new CommonException("支持成功通知缺少第三方支付单号");
        }

        //更新订单的支付状态及第三方交易单号等信息
        boolean update = lambdaUpdate()
                .eq(Orders::getId, orders.getId())
                .set(Orders::getPayTime, LocalDateTime.now())
                .set(Orders::getTradingOrderNo, tradeStatusMsg.getTradingOrderNo())
                .set(Orders::getTradingChannel, tradeStatusMsg.getTradingChannel())
                .set(Orders::getTransactionId, tradeStatusMsg.getTransactionId())
                .set(Orders::getPayStatus, OrderPayStatusEnum.PAY_SUCCESS.getStatus())
                .set(Orders::getOrdersStatus, OrderStatusEnum.DISPATCHING.getStatus())
                .update();

        if(!update){
            System.out.println("支付失败"+orders.getId());
            throw new CommonException("更新订单"+orders.getId()+"支付失败");
        }
    }

    @Override
    public void cancel(OrderCancelDTO orderCancelDTO) {

        //查询订单信息
        Orders byId = this.getById(orderCancelDTO.getId());
        if(ObjectUtils.isNull(byId)){
            throw new CommonException("找不到yao取消的订单,订单号");
        }

        //订单状态
        Integer ordersStatus = byId.getOrdersStatus();
        //根据订单状态执行取消逻辑
        if(OrderStatusEnum.NO_PAY.getStatus()==ordersStatus){
            //订单状态为未支付的
            cacelbynopage(orderCancelDTO);
        }else if(OrderStatusEnum.DISPATCHING.getStatus()==ordersStatus){
            //状态为派单中//进行退款操作
            iOrdersManagerService.refund(orderCancelDTO);
             //调用第三方平台 进行退款
             iOrdersManagerService.tuikai(orderCancelDTO);
        }else {
            throw new CommonException("当前订单状态不支持取消");
        }
    }

    @Transactional
    public void refund(OrderCancelDTO orderCancelDTO) {
        Orders orders = this.getById(orderCancelDTO.getId());
        //查找一下订单是否存在
        if(ObjectUtils.isNull(orders)){
            throw new CommonException("订单不存在");
        }

        //我们进行添加退款记录表
        OrdersCanceled ordersCanceled = new OrdersCanceled();
        ordersCanceled.setId(orders.getId());
        ordersCanceled.setCancelTime(LocalDateTime.now());
        ordersCanceled.setCancelReason(orderCancelDTO.getCancelReason());
        ordersCanceled.setCreateTime(orders.getCreateTime());
        //然后 修改状态
        boolean update = lambdaUpdate()
                .eq(Orders::getId, orders.getId())
                .set(Orders::getOrdersStatus, OrderStatusEnum.CLOSED.getStatus())
                .set(Orders::getPayStatus, OrderRefundStatusEnum.REFUNDING.getStatus())
                .update();

        if(!update){
            throw new CommonException("更改状态失败"+orders.getId());
        }
        //添加退款表
        OrdersRefund ordersRefund = new OrdersRefund();
        ordersRefund.setTradingOrderNo(orders.getTradingOrderNo());
        ordersRefund.setRealPayAmount(orders.getRealPayAmount());
        ordersRefund.setId(orders.getId());
        ordersRefund.setCreateTime(LocalDateTime.now());

        int insert = ordersRefundMapper.insert(ordersRefund);
        if(insert<0){
            throw new CommonException("退款表数据添加失败");
        }
    }

    @Override
    public void tuikai(OrderCancelDTO orderCancelDTO) {

        //判断一下订单是否存在
        Orders byId = this.getById(orderCancelDTO.getId());
        if(ObjectUtils.isNull(byId)){
           throw new CommonException("订单不存在");
        }
        ExecutionResultResDTO executionResultResDTO =null;
        try {
             executionResultResDTO = refundRecordApi.refundTrading(byId.getTradingOrderNo(), byId.getRealPayAmount());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(ObjectUtils.isNotNull(executionResultResDTO)){

            iOrdersManagerService.tigjttuik(byId,executionResultResDTO);
        }

    }

    @Override
    public void tigjttuik(Orders byId, ExecutionResultResDTO executionResultResDTO) {

        //第一步 判断一下订单是否存在
        Orders byId1 = this.getById(byId.getId());
        if(ObjectUtils.isNull(byId)){
            throw new CommonException("订单不存在");
        }
        Integer refundStatus = executionResultResDTO.getRefundStatus();
        //订单存在的话 我们判断一下 是否是退款中的状态
        if(refundStatus.equals(OrderRefundStatusEnum.REFUND_FAIL.getStatus())){
            //如果是退款失败的话 我们进行修改状态
            refundStatus=OrderRefundStatusEnum.REFUND_FAIL.getStatus();
        }else if(refundStatus.equals(OrderRefundStatusEnum.REFUND_SUCCESS.getStatus())){
            refundStatus=OrderRefundStatusEnum.REFUND_SUCCESS.getStatus();
        }

        //如果是退款中的话 不做处理
        if(refundStatus.equals(OrderRefundStatusEnum.REFUNDING.getStatus())){
            return;
        }

        //如果退款的状态不是退款中的话 我们进行修改状态
        boolean update = lambdaUpdate()
                .eq(Orders::getId, byId1.getId())
                .set(Orders::getOrdersStatus, OrderStatusEnum.CLOSED.getStatus())
                .set(Orders::getRefundStatus, refundStatus)
                .set(ObjectUtil.isNotEmpty(executionResultResDTO.getRefundNo()), Orders::getRefundNo, executionResultResDTO.getRefundNo())
                .set(ObjectUtil.isNotEmpty(executionResultResDTO.getRefundId()), Orders::getRefundId, executionResultResDTO.getRefundId())
                .update();

        if(!update){
            throw new CommonException("退款状态更新失败");
        }
    }



    public void hshfsdh(Orders orders,ExecutionResultResDTO executionResultResDTO){
        //第一步判断订单是否存在
        Orders byId = this.getById(orders.getId());

        if(!ObjectUtil.isNotNull(byId)){
            throw new CommonException("订单不存在");
        }
        //判断一下返回来的支付状态 是否成功 或者失败
        //初始化订单状态
        Integer refundStatus = executionResultResDTO.getRefundStatus();
        if(ObjectUtils.equal(refundStatus,OrderRefundStatusEnum.REFUND_FAIL.getStatus())){
            refundStatus=OrderRefundStatusEnum.REFUND_FAIL.getStatus();
        }else if(ObjectUtils.equal(refundStatus,OrderRefundStatusEnum.REFUND_SUCCESS.getStatus())){
            refundStatus=OrderRefundStatusEnum.REFUND_SUCCESS.getStatus();
        }

        //如果是退款中 将不需要做任何处理
        if(ObjectUtils.equal(refundStatus,OrderRefundStatusEnum.REFUNDING.getStatus())){
            refundStatus=OrderRefundStatusEnum.REFUNDING.getStatus();
        }

        //如果不是退款中 那就进行修改状态即可
        boolean update = lambdaUpdate()
                .eq(Orders::getId, orders.getId())
                .set(Orders::getOrdersStatus, OrderStatusEnum.CLOSED.getStatus())
                .set(Orders::getRefundStatus, refundStatus)
                .set(ObjectUtil.isNotNull(executionResultResDTO.getRefundNo()), Orders::getRefundNo, executionResultResDTO.getRefundNo())
                .set(ObjectUtil.isNotNull(executionResultResDTO.getRefundId()), Orders::getRefundId, executionResultResDTO.getRefundId())
                .update();

        //判断一下是否 更新状态成功
        if(!update){
            throw new CommonException("退款成功");
        }
    }

    private NativePayResDTO generatecode(Orders orders, PayChannelEnum tradingChannel) {

        //判断支付渠道
      Long enter =ObjectUtils.equals(PayChannelEnum.ALI_PAY,tradingChannel)?tradeProperties.getAliEnterpriseId():tradeProperties.getWechatEnterpriseId();

      //构造支付请求 参数
        NativePayReqDTO nativePayReqDTO = new NativePayReqDTO();
        //商户号
        nativePayReqDTO.setEnterpriseId(enter);
        //业务系统标识
        nativePayReqDTO.setProductAppId("jzo2o.orders");
        //家政订单号
        nativePayReqDTO.setProductOrderNo(orders.getId());
        //支付渠道
        nativePayReqDTO.setTradingChannel(tradingChannel);
        //支付金额
        nativePayReqDTO.setTradingAmount(new BigDecimal(0.01));
        //备注信息
        nativePayReqDTO.setMemo(orders.getServeItemName());
        //判断是否切换支付渠道
        if(ObjectUtil.isNotEmpty(orders.getTradingChannel())&&ObjectUtil.notEqual(orders.getTradingChannel(),tradingChannel.toString())){

            nativePayReqDTO.setChangeChannel(true);
        }

        //生成支付二维码
        NativePayResDTO downLineTrading = nativePayApi.createDownLineTrading(nativePayReqDTO);
        if(ObjectUtils.isNotNull(downLineTrading)){


            boolean update = lambdaUpdate()
                    .eq(Orders::getId, downLineTrading.getProductOrderNo())
                    .set(Orders::getTradingOrderNo, downLineTrading.getTradingOrderNo())
                    .set(Orders::getTradingChannel, downLineTrading.getTradingChannel())
                    .update();

            if(!update){
                throw new CommonException("订单"+orders.getId()+"请求支付更新交易单");
            }
        }


        return downLineTrading;
    }

    @Resource
    IOrdersCanceledService ordersCanceledService;

    @Transactional(rollbackFor = Exception.class)
    public void cacelbynopage(OrderCancelDTO cancelDTO){

        //保存取消订单记录
        OrdersCanceled ordersCanceled = BeanUtil.toBean(cancelDTO, OrdersCanceled.class);
        ordersCanceled.setCancellerId(UserContext.currentUser().getId());
        ordersCanceled.setCancelerName(UserContext.currentUser().getName());
        ordersCanceled.setCancellerType(UserContext.currentUser().getUserType());
        ordersCanceled.setCancelTime(LocalDateTime.now());
        ordersCanceledService.save(ordersCanceled);
        //更新订单状态为取消订单
        OrderUpdateStatusDTO build = OrderUpdateStatusDTO.builder()
                .id(ordersCanceled.getId())
                .originStatus(OrderPayStatusEnum.NO_PAY.getStatus())
                .targetStatus(OrderStatusEnum.CANCELED.getStatus())
                .build();
        UpdateWrapper<Orders> ordersUpdateWrapper = new UpdateWrapper<>();
        ordersUpdateWrapper.lambda().set(Orders::getPayStatus,build.getOriginStatus())
                .set(Orders::getOrdersStatus,build.getTargetStatus())
                .eq(Orders::getId,build.getId());
        boolean update = this.update(ordersUpdateWrapper);
        if(!update){
          throw new DbRuntimeException("订单取消时间处理失败");
      }
    }


}
